package com.example.videoplayer.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
import reactor.core.publisher.UnicastProcessor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class VideoWebSocketHandler implements WebSocketHandler {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final UnicastProcessor<String> messageProcessor = UnicastProcessor.create();

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        sessions.put(session.getId(), session);
        
        // 广播新用户加入消息
        broadcastUserCount();

        return session.receive()
                .map(message -> message.getPayloadAsText())
                .doOnNext(message -> handleMessage(session, message))
                .doFinally(signalType -> {
                    sessions.remove(session.getId());
                    broadcastUserCount();
                })
                .then();
    }

    private void handleMessage(WebSocketSession session, String message) {
        try {
            Map<String, Object> messageMap = objectMapper.readValue(message, Map.class);
            String type = (String) messageMap.get("type");
            
            switch (type) {
                case "chat":
                    broadcastMessage(messageMap);
                    break;
                case "sync":
                    handleVideoSync(messageMap);
                    break;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    private void broadcastMessage(Map<String, Object> message) {
        String messageJson;
        try {
            messageJson = objectMapper.writeValueAsString(message);
            sessions.values().forEach(session -> 
                session.send(Mono.just(session.textMessage(messageJson))).subscribe()
            );
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    private void broadcastUserCount() {
        Map<String, Object> message = new HashMap<>();
        message.put("type", "userCount");
        message.put("count", sessions.size());
        broadcastMessage(message);
    }

    private void handleVideoSync(Map<String, Object> message) {
        // 处理视频同步消息
        broadcastMessage(message);
    }
} 